package com.market.plus.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.market.plus.core.model.ImageSizeType;
import com.market.plus.core.model.MetadataFile;
import com.market.plus.core.model.Picture;
import com.market.plus.core.service.MarketOCMService;

@Controller
public class ContentManagementController {

   private static final Logger Log = Logger.getLogger(ContentManagementController.class);

   private MarketOCMService marketOCMService;

   @Autowired
   public ContentManagementController(
         @Qualifier("marketOCMService")MarketOCMService marketOCMService){
      this.marketOCMService = marketOCMService;
   }

   @RequestMapping(value = "/getContent/{fileGuid}/small", method = RequestMethod.GET)
   public void downloadSmallPicture(@PathVariable("fileGuid")String fileGuid,ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception {
      download(fileGuid, model, request, response, ImageSizeType.SMALL);
   }

   @RequestMapping(value = "/getContent/{fileGuid}/medium", method = RequestMethod.GET)
   public void downloadMediumPicture(@PathVariable("fileGuid")String fileGuid,ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception {
      download(fileGuid, model, request, response, ImageSizeType.MEDIUM);
   }

   @RequestMapping(value = "/getContent/{fileGuid}", method = RequestMethod.GET)
   public void downloadPicture(@PathVariable("fileGuid")String fileGuid,ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception {
      download(fileGuid, model, request, response, ImageSizeType.REAL);
   }

   @RequestMapping(value = "/getFile/{albumUUID}/pictures", method = RequestMethod.GET)
   public @ResponseBody List<Picture> getPictures(@PathVariable("albumUUID")String albumUUID) throws Exception {
      List<Picture> pictures = this.marketOCMService.getPictures(albumUUID);
      return pictures;
   }

   private void download(String fileGuid,ModelMap model,HttpServletRequest request,HttpServletResponse response,ImageSizeType imageSizeType) throws Exception {
      MetadataFile file = null;
      if ("0".equals(fileGuid)){
         file = getGuestAvatar(request);
      }else {
         try {
            file = this.marketOCMService.getFile(fileGuid, imageSizeType);
         } catch (Exception e){
            Log.error(e.getMessage(), e);
            try {
               file = getGuestAvatar(request);
            } catch (Exception e1) {
               Log.error(e1.getMessage(), e1);
               throw e1;
            }
         }
      }
      if (file.getInputStream() == null){
         file = getGuestAvatar(request);
      }
      updateResponse(file, response);
   }

   private MetadataFile getGuestAvatar(HttpServletRequest request) throws FileNotFoundException{
      String guestAvatarRealPath = WebUtils.getRealPath(request.getSession().getServletContext(), "images/guest_avatar.png");
      File file = new File(guestAvatarRealPath);
      FileInputStream fileInputStream = new FileInputStream(file);
      MetadataFile metadataFile  = new MetadataFile();
      metadataFile.setFilename(file.getName());
      metadataFile.setLength((new Long(file.length())).intValue());
      metadataFile.setType("image/png");
      metadataFile.setInputStream(fileInputStream);
      return metadataFile;
   }
   
   private void updateResponse(MetadataFile file, HttpServletResponse response) throws IOException{
      response.setContentType(file.getType());
      response.setContentLength(file.getLength());
      response.setHeader("Content-Disposition","attachment; filename=\"" + file.getFilename() +"\"");
      FileCopyUtils.copy(file.getInputStream(), response.getOutputStream());
   }
}
